package com.example.soss.controller;

import com.example.soss.annotation.AccessLimit;
import com.example.soss.annotation.OperationLog;
import com.example.soss.entity.*;
import com.example.soss.service.CourseService;
import com.example.soss.util.UserContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

@Controller
@RequiredArgsConstructor
@Slf4j
public class CourseController {

    private final CourseService courseService;

    private final ThymeleafViewResolver thymeleafViewResolver;

    @OperationLog("查看选课列表")
    @GetMapping(value = "/list",  produces = "text/html")
    @AccessLimit("page")
    @ResponseBody
    public String getList(Model model, Page page, int flag,
                          HttpServletRequest request, HttpServletResponse response) {

//        int currentPage = new Random().nextInt(5) + 1;
        String key = flag + ":" + page.getCurrentPage();
        String html = courseService.getPageCache(key);
        //如果缓存为空，从数据库中获取放入缓存
        if (html == null) {
            Student student = UserContextHolder.getUser();
            int totalSize = courseService.getAllCourseCount(flag);
            List<Course> courseList = courseService.getAllCourseList(page.getCurrentPage(), page.getLimit(), flag);

            page.setTotalSize(totalSize);
            page.setPath("/list");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");

            model.addAttribute("courses", courseList);
            model.addAttribute("loginUser", student);
            model.addAttribute("flag", flag);

            IWebContext webContext = new WebContext(request, response, request.getServletContext(),
                    response.getLocale(), model.asMap());
            html = thymeleafViewResolver.getTemplateEngine().process("list", webContext);

            courseService.setPageCache(key, html);
            log.info("手动渲染页面----------------------");
            return html;
        } else {
            log.info("从缓存中获取页面------------------------");
            return html;
        }
    }


    @OperationLog("选课")
    @PostMapping("/selectCourse")
    @ResponseBody
    @AccessLimit("select")
    public Result selectCourse(int courseId) {
//        int courseId = new Random().nextInt(30) + 1;
//        int stuId = new Random().nextInt(1500000);
        Student student = UserContextHolder.getUser();
        if (student == null) {
            return Result.failure(ResultEnum.NOT_LOGIN);
//            return courseService.selectCourseByDB(courseId, stuId);
        }
        return courseService.selectCourseByDB(courseId, student.getId());
    }


    @OperationLog("查看已选择的课程")
    @GetMapping("/selectedCourse")
    public String selectedCourse(Model model) {

        Student user = UserContextHolder.getUser();
        if (user != null) {
            Course selectedCourse = courseService.getSelectedCourse(user.getId());
            model.addAttribute("selectedCourse", selectedCourse);
            model.addAttribute("loginUser", user);
        }
        return "result";
    }



    @OperationLog("轮询获取选课结果")
    @GetMapping("/getResult")
    @ResponseBody
    public Result getResult(int courseId) {
        return courseService.getResult(courseId);
    }



    @OperationLog("退课")
    @PostMapping("/dropCourse")
    @ResponseBody
    public Result dropCourse(int courseId) {
        Student student = UserContextHolder.getUser();
        if (student == null) return Result.failure(ResultEnum.NOT_LOGIN);
        return courseService.dropCourse(courseId, student.getId());
    }

    @OperationLog("添加课程")
    @PostMapping("/addCourse")
    @ResponseBody
    public Result addCourse(@Valid Course course) {
        return courseService.addCourse(course);
    }


    @OperationLog("删除课程")
    @PostMapping("/deleteCourse")
    @ResponseBody
    public Result deleteCourse(int courseId) {
        return courseService.deleteCourse(courseId);
    }

    @OperationLog("编辑课程")
    @PostMapping("/updateCourse")
    @ResponseBody
    public Result updateCourse(@Valid Course course) {
        return courseService.updateCourse(course);
    }
}
